<template>
  <sv-page showTabBar>
    <view class="home">
      <view class="padding-tb">
        <uv-swiper
          :list="banner"
          autoplay
          circular
          showTitle
          keyName="image"
          :title-style="{ color: 'red', textAlign: 'center' }"
          previousMargin="30"
          nextMargin="30"
          radius="5"
          bgColor="transparent"
        ></uv-swiper>
      </view>
      <!-- 选择栏 -->
      <view class="cu-bar margin-top-sm">
        <view class="action sub-title text-blue" @click="openPicker">
          <text class="cuIcon-titles"></text>
          <template v-if="libInfo">
            <text class="text-bold">
              {{ libInfo?.lib_name }}
            </text>
            <text class="text-cyan margin-left text-df">
              {{ libInfo?.lib_chapter[libInfo.unit_index].value }}
            </text>
          </template>
          <text v-else>选择题库</text>
          <text class="text-sm text-ABC margin-left-sm">EXAM_LIB</text>
        </view>
      </view>
      <!-- 内容 -->
      <view class="flex" style="height: 920rpx">
        <!-- 左 -->
        <view class="flex-sub flex-col-hc justify-around">
          <view
            v-for="item in sideMenuLeft"
            :key="item.path"
            class="flex-col-vhc"
            @click="onMenu(item)"
          >
            <view class="bg-gradual-blue side-btn text-xxl" :class="item.icon"></view>
            <view class="text-sm margin-top-xs">{{ item.name }}</view>
          </view>
        </view>
        <!-- 中 -->
        <view class="flex-sub flex-col-hc justify-evenly">
          <view class="bg-gradual-blue mode-btn" @click="getExamPaper('recite')">
            <view class="text-lg text-bold">背题模式</view>
            <view class="margin-top-sm text-tyblue">快速记忆</view>
          </view>
          <view class="bg-gradual-green mode-btn" @click="getExamPaper('practice')">
            <view class="text-lg text-bold">刷题模式</view>
            <view class="margin-top-sm text-yellow">实战演练</view>
          </view>
          <view class="bg-gradual-orange mode-btn" @click="getExamPaper('exam')">
            <view class="text-lg text-bold">单元检测</view>
            <view class="margin-top-sm text-yellow">阶段训练</view>
          </view>
          <view class="bg-gradual-red mode-btn" @click="getExamPaper('exam', 1)">
            <view class="text-lg text-bold">模拟考试</view>
            <view class="margin-top-sm text-olive">仿真冲刺</view>
          </view>
        </view>
        <!-- 右 -->
        <view class="flex-sub flex-col-hc justify-around">
          <view
            v-for="item in sideMenuRight"
            :key="item.path"
            class="flex-col-vhc"
            @click="onMenu(item)"
          >
            <view class="bg-gradual-blue side-btn text-xxl" :class="item.icon"></view>
            <view class="text-sm margin-top-xs">{{ item.name }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 选择器 -->
    <uv-picker
      ref="libPickerRef"
      keyName="value"
      :columns="libColumns"
      @confirm="confirmPicker"
      @change="changePicker"
    ></uv-picker>
  </sv-page>
</template>

<script setup>
import { computed, nextTick, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { store } from '@/uni_modules/sv-id-pages/common/store'
import {
  buyLibList,
  correctNumInc,
  doneExamAdd,
  errorExamAdd,
  errorNumInc,
  favExamAdd,
  favExamDelete,
  favExamList
} from '@/service/api/record.js'
import { judgeLogin } from '@/utils/util'
import { useSysStore } from '@/store/sys'
import { isEmpty } from 'lodash-es'
import { examList } from '@/service/api/exam'

const libInfo = computed({
  get() {
    return useSysStore().getConfig().curLib
  },
  set(newVal) {
    useSysStore().setConfig({
      curLib: newVal
    })
  }
})

onShow(async () => {
  if (store.hasLogin) {
    await handleBuyLib()
  }
})

const banner = [
  {
    image: 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
    title: '丙辰中秋，欢饮达旦，大醉，作此篇，兼怀子由'
  },
  {
    image: 'https://cdn.uviewui.com/uview/swiper/swiper1.png',
    title: '明月几时有？把酒问青天'
  },
  {
    image: 'https://cdn.uviewui.com/uview/swiper/swiper3.png',
    title: '不知天上宫阙，今夕是何年'
  }
]

const libPickerRef = ref()
const libColumns = ref([[]])

async function openPicker() {
  // 判断登录
  const isLogin = judgeLogin()
  // 未登录不予操作
  if (!isLogin) return

  if (isEmpty(libColumns.value[0])) {
    uni.showToast({
      title: '好像还没有购买题库哦，去大厅看看吧~',
      icon: 'none'
    })
    return
  }

  libPickerRef.value.open()
}

async function handleBuyLib() {
  const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
  const buyLibArr = buyLibRes.data || []
  const handleColumn = buyLibArr.map((item) => {
    return {
      value: item.lib_name,
      key: item.lib_id,
      chapter: item.lib_chapter
    }
  })
  libColumns.value = [handleColumn] // 二维数组

  nextTick(() => {
    // 选择器初始化设置
    if (isEmpty(libInfo.value)) {
      libPickerRef.value.setColumnValues(1, handleColumn[0].chapter)
    } else {
      libPickerRef.value.setColumnValues(1, libInfo.value.lib_chapter)
      const libIndex = libColumns.value[0].findIndex((item) => item.key === libInfo.value.lib_id)
      libPickerRef.value.setIndexs([libIndex, libInfo.value.unit_index], true)
    }
  })
}

async function confirmPicker(e) {
  libInfo.value = {
    lib_id: e.value[0].key,
    lib_name: e.value[0].value,
    lib_chapter: e.value[0].chapter,
    unit_index: e.indexs[1]
  }
}

function changePicker(e) {
  libPickerRef.value.setColumnValues(1, e.value[0].chapter)
}

async function getExamPaper(type, args) {
  if (isEmpty(libInfo.value)) {
    uni.showToast({
      title: '还没有选择题库哦',
      icon: 'none'
    })
    return
  }
  let unit = libInfo.value.lib_chapter[libInfo.value.unit_index].key
  if (type == 'exam' && args == 1) {
    unit = ''
  }
  uni.navigateTo({
    url: '/uni_modules/sv-exam-plus/pages/exam/exam',
    success: async (res) => {
      res.eventChannel.emit('e-transmit-exams', {
        param: {
          from_lib: libInfo.value.lib_id,
          unit,
          pagesize: -1
        },
        opt: {
          lib_name: libInfo.value.lib_name,
          type: type
        },
        apifunc: {
          examList,
          favExamAdd,
          favExamDelete,
          favExamList,
          correctNumInc,
          errorNumInc,
          errorExamAdd,
          doneExamAdd
        }
      })
    }
  })
}

// 左右侧栏菜单
const sideMenuLeft = [
  { name: '已购题库', icon: 'sv-icons-agreements', path: '/pages/menu/lib/lib-buy' },
  { name: '收藏题库', icon: 'sv-icons-agreements', path: '/pages/menu/lib/lib-fav' },
  { name: '我的课程', icon: 'sv-icons-agreements', path: '' },
  { name: '课题精选', icon: 'sv-icons-agreements', path: '' }
]
const sideMenuRight = [
  { name: '错题本', icon: 'sv-icons-agreements', path: '/pages/menu/exam/exam-wrong' },
  { name: '收藏试题', icon: 'sv-icons-agreements', path: '/pages/menu/exam/exam-fav' },
  { name: '答题历史', icon: 'sv-icons-agreements', path: '/pages/menu/exam/exam-history' },
  { name: '成绩记录', icon: 'sv-icons-agreements', path: '/pages/menu/exam/exam-record' }
]

function onMenu(item) {
  // 判断登录
  const isLogin = judgeLogin()
  // 未登录不予操作
  if (!isLogin) return

  if (item.path) {
    uni.navigateTo({
      url: item.path
    })
  } else {
    uni.showToast({
      title: '敬请期待',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss">
.home {
  // height: var(--page-main-height);

  .side-btn {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .mode-btn {
    width: 180rpx;
    height: 180rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 40rpx;
    transition: all 0.3s ease;
    box-shadow: inset 2px 2px 2px 0px rgba(255, 255, 255, 0.5), 7px 7px 20px 0px rgba(0, 0, 0, 0.1),
      4px 4px 5px 0px rgba(0, 0, 0, 0.1);
    &:active {
      box-shadow: 4px 4px 6px 0 rgba(255, 255, 255, 0.5), -4px -4px 6px 0 rgba(116, 125, 136, 0.5),
        inset -4px -4px 6px 0 rgba(255, 255, 255, 0.2), inset 4px 4px 6px 0 rgba(0, 0, 0, 0.4);
    }
  }
}
</style>
